<?php
App::uses('AppController', 'Controller');

class ArticlesController extends AppController {
	
	public $helpers = array('Html', 'Form');
	public $components = array();


	public function beforeFilter() {
		parent::beforeFilter();
		// Allow users to register and logout.
		$this->Auth->allow('index', 'show');
	}


	public function index(){
		$this->paginate = array(
			'conditions' => array(
				'Article.status ' => ARTICLE_PUBLISHED
			),
			'fields' => array(
				'Article.id', 'Article.title', 'Article.short_content', 'Article.created'
			),
			'order'=> array(
				'Article.created'=> 'DESC'
			),
			'limit' => ARTICLES_PAGE_LIMIT,
		);
		$articles = $this->paginate('Article');

		$this->set('articles', $articles);
		$this->set('title_for_layout', __('Blbosti | Prečo práve ja?'));
	}


	public function show($id){
		$id = (int) $id;

		$article = $this->Article->findById($id);


		if (empty($article)) {
			throw new NotFoundException(__('Stránka neexistuje'));
		}

		$this->set('article', $article);
		$this->set('title_for_layout', $article['Article']['title'] . ' | ' .  __('Prečo práve ja?'));
	}



	public function admin_index(){
		$articles = $this->Article->find('all');
		$this->set('articles', $articles);
	}


	public function admin_add(){
		if($this->request->is('post')){
			$this->Article->set($this->request->data);
			if ($this->Article->save()) {
				$this->set('formMessage', __('Príspevok bol odoslaný.'));
				$this->redirect('index');
			}

		}
	}


	public function admin_view($id = null){
		if (!$id) {
			throw new NotFoundException(__('Invalid post'));
		}

		$article = $this->Article->findById($id);
		if (!$article) {
			throw new NotFoundException(__('Invalid post'));
		}
		$this->set('article', $article);
	}


	public function admin_edit($id = null) {

		if (!$id) {
			throw new NotFoundException(__('Invalid post'));
		}

		$article = $this->Article->findById($id);
		if (!$article) {
			throw new NotFoundException(__('Invalid post'));
		}

		if ($this->request->is(array('post', 'put'))) {
			$this->Article->id = $id;
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__('Your post has been updated.'));
				return $this->redirect(array('action' => 'index'));
			}
			$this->Session->setFlash(__('Unable to update your post.'));
		}

		if (!$this->request->data) {
			$this->request->data = $article;
		}
	}


	public function admin_delete($id) {
	    if ($this->request->is('get')) {
	        throw new MethodNotAllowedException();
	    }

	    if ($this->Article->delete($id)) {
	        $this->Session->setFlash(
	            __('The post with id: %s has been deleted.', h($id))
	        );
	    }else {
	        $this->Session->setFlash(
	            __('The post with id: %s could not be deleted.', h($id))
	        );
	    }
	    return $this->redirect(array('action' => 'index'));
	}

	
}
